Ext.namespace("Milan.ajaxutility");

/**
 * 用ajax方式提交请求，请求的url和参数可以来自于url参数也可以来自于form参数
 * config参数的对象属性:
 * form : 要提交的表单id(可选，此参数不设置时，url参数必须设置。使用此参数时，将form.action作为url，form内的所有可提交对象做为参数)
 * url:要提交的url(可选，此参数不设置时，form参数必须设置。如果url和form同时设置时，则form参数生效)
 * params:请求的参数，应该为&a=?&b=?形式。第一个&没有也可以，当使用form时，将form的参数将加上此参数一起提交。当使用url时，最终请求为url+params
 * success : 请求成功返回后的回调,形式为function(response)
 * failure : 请求失败后的回调,形式为function(response)
 * onException:请求成功，但返回的内容是服务端异常信息时的回调函数，正常会由Milan.ajaxutility.AjaxRequestInteceptor处理后再交onException()
 * method : form提交的方式 (可选,默认为post)
 * displayMasker:调用时是否显示遮罩层，默认为true
 * displayLoading:调用时是否显示”数据载入中“图片，默认为true
 * 
 */

Milan.ajaxutility.formSubmit = function(config)
{
	config = config || {};
	var formObj = new Object();
	if(config["form"]) formObj = $(config["form"]);
	var vurl = formObj.action||config["url"];
	var vmethod = formObj.method||config["method"]||"POST";
		
	if(formObj&&formObj.elements)
	{
		if(!Milan.commonutils.formEleValidate(formObj))
		{
			return false;
		}
	}
	
	function sucFun(response, options)
	{
		setTimeout(function(){
			$("trueLoadingDiv").hide();
			$("loadingDiv").hide();
		},10);
		Milan.ajaxutility.AjaxRequestInteceptor(response, options, config["success"], config);
	}
	
	function failFun()
	{
		alert("在请求服务时发生了错误，请检查网络连接或联系系统管理员，谢谢！");
		if (config && config['failure'])
			config['failure'].call();
		setTimeout(function(){
			$("trueLoadingDiv").hide();
			$("loadingDiv").hide();
			},10);			
	}


	/*
	 * 控制是否显示半透明遮罩层
	 */
	if(typeof(config["displayMasker"]) == "undefined")
		config["displayMasker"] = true;
	
	/*
	 * 控制是否显示“正在加载”图片
	 */
	if(typeof(config["displayLoading"]) == "undefined")
		config["displayLoading"] = true;
	
	if(config["displayMasker"])
	{
		Milan.ajaxutility.setLoadingDivHeight();
		$("loadingDiv").show();	
	}
	
	if(config["displayLoading"])
	{
		$("trueLoadingDiv").style.top = document.body.scrollTop + (document.body.offsetHeight/2);
		$("trueLoadingDiv").show();
	}
		
	
	Milan.ajax.request({
		url: vurl,
		method : vmethod,
		params : config["params"],
		form : config["form"],
		success : sucFun,
		failure : failFun
    	});
}

Milan.ajaxutility.setLoadingDivHeight = function(){
	//var bodyHeight = document.body.scrollHeight;
	//var botHeight = $("bottomFrame").positionedOffset().top+$("bottomFrame").getHeight();
	//$("loadingDiv").style.height = ((bodyHeight>botHeight)?bodyHeight:botHeight)+"px";
};
/**
 * 用ajax的方式更新指定的容器中的内容
 * 
 * method:请求方式，默认为post
 * url:请求用的url，如果要提交的内容是form,请设置formid。
 * element:要更新的容器，参见updateContainer中的container
 * config:和formSubmit方法一样，增加了一个onUpdated回调，用于在更新容器内容后的回调。success会早于onUpdated被回调，其发生的时机是请求成功返回时。所以本函数中success可以视为beforeUpdate。

 * 注：updateContentUseAjax实际是封装了formSubmit，在其onSuccess中调用了updateContainer.所以会执行返回内容中的js代码
 * 因历史和应用的方便，此函数仍然使用顺序参数，而非对象参数。
 * 实际上method,url两个参数，会被自动放入config参数并提供给formSubmit;所以调用这个函数时,config.method和config.url实际无效。
*/
Milan.ajaxutility.updateContentUseAjax = function (method,url,element,config)
{
	if (!config) 
		config = {};
	
	config["method"] = method;
	
	Milan.ajaxutility.isFormElement(url)?config["form"]=url:config["url"]=url
	
		
	//如果element是dialog,则说明不需要出现masker		
	if(Milan.ajaxutility.isMilanDialog(element)) 	
		config["displayMasker"] = false;	
	
	var onExceptionCallBack = config["onException"];
	config["onException"] = function(response,options)
	{
		if (Milan.ajaxutility.isMilanTab(element))
			Milan.tabbarManager.removeTab(element); //如果要更新的element是tab的话，出现错误时则关闭该tab
				
		if(Milan.ajaxutility.isMilanDialog(element)) element.closeDialog();	//如果要更新的element是dialog的话，出现错误则关闭dialog
		if (onExceptionCallBack) onExceptionCallBack();
	}
		
	var onFailCallBack =  config["failure"];
	config["failure"] = function(response,options)
	{
		if (Milan.ajaxutility.isMilanTab(element))
			Milan.tabbarManager.removeTab(element); //如果要更新的element是tab的话，出现错误时则关闭该tab
				
		if(Milan.ajaxutility.isMilanDialog(element)) element.closeDialog();	//如果要更新的element是dialog的话，出现错误则关闭dialog	
		
		if (onFailCallBack) return onFailCallBack();
		return true;
	}
	
	
	var onUpdatedCallBack = function(response,options)
	{
		if(Milan.ajaxutility.isMilanDialog(element))	//如果是MilanDialog则帮它show一下
		{
			element.show();
		}
		if(config["onUpdated"]) config["onUpdated"].call(this,response,options);
	}
	
	var onSuccess = config["success"];
	config["success"] = function(response,options)
	{
		if (onSuccess) onSuccess(response,options);
		Milan.ajaxutility.updateContainer(element,response.responseText,onUpdatedCallBack);
	}
	
	try
	{
		Milan.ajaxutility.formSubmit(config);
	}
	catch(e)
	{
		throw e;
	}
}
/**
 * 判断传入的参数是否是Milan JS框架中的Dialog类型
 */
Milan.ajaxutility.isMilanDialog = function(element)
{
	return (element&&element.closeDialog);
}

/**
 * 判断传入的参数是否是Milan JS框架中的Tab类型
 */
Milan.ajaxutility.isMilanTab = function(element)
{
	if (typeof element == "string" && element.indexOf("index_tab_") > -1)
		return true;
	else
		return false;
}
/**
 * 判断传入的参数是否是Milan JS框架中的UserSelectorTab类型
 */
Milan.ajaxutility.isMilanUserSelectorTab = function(element)
{
	if (typeof element == "string" && element.indexOf("userSelector_tab_") > -1)
		return true;
	else
		return false;
}

/**
 * 判断传入的参数是否是一个存在的控件
 */
Milan.ajaxutility.isFormElement = function(element)
{
	if ($(element))
		return true;
	else
		return false;
}



/**
 * 在ajax请求执行完毕后与执行完毕后执行的回调函数之间的切面
 * 
 * @param {Object} response          XMLHttp对象
 * @param {Object} option            
 * @param {Object} successCallBack   ajax请求执行完毕后的回调
 * @author WinyWan
 */
Milan.ajaxutility.AjaxRequestInteceptor = function(response,option,successCallBack,config)
{
	
	var XMLDoc = response.responseXML;
	var textDoc = response.responseText;
	var result,errorType,errorTypeInfo="",message,isNeedLogin;
	if(XMLDoc&&XMLDoc.childNodes&&XMLDoc.getElementsByTagName("result").length>0)
	{
		result = XMLDoc.getElementsByTagName("result")[0].firstChild.nodeValue;
		isNeedLogin = XMLDoc.getElementsByTagName("is-need-login")[0].firstChild.nodeValue;
		errorType = XMLDoc.getElementsByTagName("error-type")[0].firstChild.nodeValue;
		message = XMLDoc.getElementsByTagName("error-message")[0].firstChild.nodeValue;		
		if(XMLDoc.getElementsByTagName("error-title")&&XMLDoc.getElementsByTagName("error-title")[0]&&XMLDoc.getElementsByTagName("error-title")[0].firstChild)
		{
			errorTypeInfo = XMLDoc.getElementsByTagName("error-title")[0].firstChild.nodeValue;
		}
		if(errorTypeInfo==""&&errorType==1){
		    errorTypeInfo = "错误";
		}else if(errorTypeInfo==""&&errorType == 2){ 
			errorTypeInfo = "提示信息";
		}
		if (!eval(result))
		{
			if(errorType==1)
			{
				
			}
			if (eval(isNeedLogin)) 
			{
				Milan.commonutils.createModelPop({
					title: errorTypeInfo,
					modelType:Milan.commonutils.MODELTYPE_CONFIRM,
					message:"重新超时请重启登录!",
					confirmCallback:function()
					{
						window.location = "index.do";//跳回系统首页
					},
					cancelCallback: function()
					{
						if(config&&config.onException) 
							return config.onException();
						return true;
					}
				});				

			}
			else 
			{
				Milan.commonutils.createModelPop({
					title: errorTypeInfo,
					modelType:Milan.commonutils.MODELTYPE_DELAYNOTIFY,
					message:message,
					confirmCallback:function()
					{
						if(config&&config.onException) config.onException();
					}
				});				
			}
		}
		if (errorType != 2) 
		{
		   if(config&&config.onException) config.onException();
		   return false;
		}
	}

	if(successCallBack)
	{
		successCallBack(response ,option);
	}
	
}

/**
 * 用content更新指定的container
 * container可以是MilanDialog,Milan.tabber和普通的可更新元素
 * 更新完成后回调onUpdatedCallBack()
 * 
 * 注：此方法会执行content中包含的js代码，并会载入content中的jsFileName标签中以";"隔开的js文件
 * 如:<jsFileName><!--js/pageJS/workplan/page_deptplanofday.js;js/pageJS/workplan/page_deptworkplanlist.js--></jsFileName>
 * 
 * 在载入js时，会自动调用符合Milan pagejs定义的docLoadBeforeCallBack和docOnReadyCallback函数。
 * 以上例：在载入page_deptplanofday.js和page_deptworkplanlist.js后，
 * 会自动调用Ext.milan.js.pagejs.workplan.page_deptplanofday.docLoadBeforeCallBack和docOnReadyCallback
 * 以及Ext.milan.pagejs.workplan.page_deptworkplanlist.docLoadBeforeCallBack和docOnReadyCallback
 * 
 * 注2：各函数调用顺序:
 * docLoadBeforeCallBack
 * updateContainer
 * docOnReadyCallback
 * onUpdatedCallBack
 */
Milan.ajaxutility.updateContainer = function(container,content,onUpdatedCallBack)
{
	var response = {};
	response.responseText = content;
	var jsName = Milan.ajaxutility.getJsFileName(response);
	var jsContent = Milan.ajaxutility.getJsContent(response);
	
	if (diswin)
		container = $(container)||eval(diswin);
	else
		container = $(container)||container;
	

	var jsFiles = jsName.split(";");

	
	Milan.ajaxutility.loadJSFiles(jsFiles,loadComplete);
	

	function loadComplete()
	{
		
		var jsUrl;
		var jsFunctions = new Array();
		var packetName = "";
		for (var i=0;i<jsFiles.length;i++)
		{
			jsUrl = jsFiles[i];
			var func = {};
			if (jsUrl.indexOf("?")>-1) 
			{
				packetName = Milan.ajaxutility.getPacketName(jsUrl.substring(0,jsUrl.indexOf("?")));
				func.beforeCallBack = packetName+".docLoadBeforeCallBack";
				func.readyCallBack = packetName+".docOnReadyCallback";
				func.params = jsUrl.substring(jsUrl.indexOf("?") + 1, jsUrl.length);
			}
			else
			{
				packetName = Milan.ajaxutility.getPacketName(jsUrl);
				func.beforeCallBack = packetName+".docLoadBeforeCallBack";
				func.readyCallBack = packetName+".docOnReadyCallback";
				func.params = "";
			}
			jsFunctions[jsFunctions.length] = func;
		}
		
		
		for (var i=0;i<jsFunctions.length;i++)
		{
			var func = jsFunctions[i];
			if (Milan.ajaxutility.isFunctionValid(func.beforeCallBack))
				eval(func.beforeCallBack+".call(this,'"+func.params+"')");
		}
			
		container = Milan.ajaxutility.updateContainer.update(container,content);		
		
		for (var i=0;i<jsFunctions.length;i++)
		{
			var func = jsFunctions[i];
			if (Milan.ajaxutility.isFunctionValid(func.readyCallBack))
				eval(func.readyCallBack+".call(this,'"+func.params+"')");
		}
		
		if (jsContent)
		{
			for(var jj = 0,jjlen=jsContent.length;jj<jjlen;jj++)
			{
				eval(jsContent[jj]);
			}
		}
		
		//如果是Chrome lite浏览器，必须把form的ousubmit变成不提交
		if (Milan.navigator.isAndroid)
		{
			var forms = document.getElementsByTagName("form");
			for (var i=0;i<forms.length;i++)
			{
				if (!forms[i].onsubmit) 
					forms[i].onsubmit=function(){return false}
			}
		}
		
		//设置div的最大高度
		jQuery(container).find("div[maxHeight]").each(function(i, ele){
			if(jQuery(this).height()>jQuery(this).attr("maxHeight")){
				jQuery(this).height(jQuery(this).attr("maxHeight"));
			}
		});
		if(Milan.navigator.isIE && Milan.navigator.version=="6.0"){//解决IE6下文字与数字对齐--事务编号
			jQuery("span.td_detail").css({"vertical-align":"baseline","display":"inline-block","cursor":"pointer"});
		}
		
		
		TransSelectChooseFromDIV(container);
		TransVirtualInputFromDIV(container);
		
		//var a = new Date().getTime();
	  	Milan.ajaxutility.transferGrid(container);			//先转换可能存在的table
	  	//alert(new Date().getTime()-a);
		if (onUpdatedCallBack) onUpdatedCallBack();

		
		/*
		 * 图标(刷新,添加,删除,附件...)鼠标事件
		 */
		jQuery(container).find("i.icon-h").each(function(i,ele){
			if(ele.className.indexOf("_disabled")<0)
			{
				jQuery(ele).hover(
					function(){
						$(this).addClassName("i-hover");
					},
					function(){
						$(this).removeClassName("i-hover");
					}
				)
			}
		});
		jQuery(container).find("input:checkbox").addClass("checkboxmiddle"); //复选框与文字对齐
		
		Milan.ajaxutility.TransAutoFixDOMObject(content);
		if (Milan.Calendar && Milan.Calendar.transferCalendar) Milan.Calendar.transferCalendar(container);
		
		
		if (onload) onload();		//调用页面上的onload
		
		
		if(content && !Milan.navigator.isAndroid)			//自动定位第一个text
		{
			setTimeout(
				function(){
					try
					{
						var inputs = jQuery(container).find("input[type='text']");
						if (inputs.length>0)
							inputs[0].focus();
					}
					catch(e)
					{
					}
				},500
			)						
		}
		
		return;
	}	
}


Milan.ajaxutility.TransAutoFixDOMObject = function(content)
{
	if (content && content.indexOf("AUTOFIX_EM")<=0)
		return;
	
	if (Milan.ajaxutility.TransAutoFixDOMObject.loadCount < 20) 
	{
		if (jQuery(".AUTOFIX_EM").length>0)
		{
			jQuery(".AUTOFIX_EM").each(
				function(i)
				{
			  	var maxWidth = jQuery(this).attr("maxWidth");
			  	if(maxWidth)
			  	{
			  		if (jQuery(this).prop("clientWidth")>maxWidth)
			  			jQuery(this).css("width",maxWidth);
			  	}
			 	}
			)
			Milan.ajaxutility.TransAutoFixDOMObject.loadCount=0;
		}
		else
		{
			Milan.ajaxutility.TransAutoFixDOMObject.loadCount++;
			setTimeout(function(){Milan.ajaxutility.TransAutoFixDOMObject(content)}, 20);			
		}
	}
	else 
	{
		Milan.ajaxutility.TransAutoFixDOMObject.loadCount=0;
		return;
	}	
}
Milan.ajaxutility.TransAutoFixDOMObject.loadCount =0;

/*
 * 用content更新指定的container
 * container可以是MilanDialog,Milan.tabber和普通的可更新元素
 * 
 * 注：此方法更新并不会执行content中包含的JS代码
 */
Milan.ajaxutility.updateContainer.update = function(container,content)
{
	if(Milan.ajaxutility.isMilanDialog(container))
	{
		return container.update(content);
	}
	else
	{
		if(container.update)
		{
			container.update(content);
			return container;
		}
		else
		{
			$(container).innerHTML = content;
			return $(container);
		}
	}
}

/*
 * 往当前页面文档中载入一个javascript文件
 * 载入完成后会回调onLoaded(jsFile,loaded),jsFile为载入的文件名，loaded为是否为本次调用载入
 * 
 * 如果js文件已经在文档中载入，则不执行，但仍会回调onLoaded函数。但回调的loaded参数为false,反之为true.
 * 
 */
Milan.ajaxutility.loadJSFile = function(jsFile,onLoaded)
{
	var docScriptFiles = document.getElementsByTagName("script");
	for (var i = docScriptFiles.length - 1; i >-1; i--) 
	{
		if (docScriptFiles[i].src && docScriptFiles[i].src.lastIndexOf(jsFile)>-1) 
		{
			/*判断jsFileName标记中js文件已存在就不执行装载，注释后每次都装载========胡作正=======*/
			//if (onLoaded) onLoaded(jsFile,false);
			//return;
		}
	}
	
	var scriptObj = document.createElement("script");
	scriptObj.src = jsFile;
	scriptObj.type = "text/javascript";
	scriptObj.onload = scriptObj.onreadystatechange = function()
	{
		if (this.readyState && this.readyState == "loading") 
			return;
		this.setAttribute("loadComplete",true);
		if (onLoaded) onLoaded(jsFile,true);
	};
	
	var headObj = document.getElementsByTagName("head")[0];
	headObj.appendChild(scriptObj);
	

}

/*
 * 载入一个js文件名的数组,全部载入完成后会调用onComplete(jsFiles)，每单个载入会调用onLoaded(jsFile,loaded)（同loadJSFile)
 * 
 * 
 */
Milan.ajaxutility.loadJSFiles = function(jsFiles,onComplete,onLoading)
{
	if (jsFiles.length==0) return;
	var loadCount = -1;
	var jsFilePathName;
	var jsUrl;

	onLoadJs();
	
	function onLoadJs(fileName)
	{
		loadCount++;
		if (onLoading) onLoading(fileName);
		if (loadCount==jsFiles.length)
		{
			if (onComplete) onComplete(jsFiles);
			return;
		}
		jsUrl = jsFiles[loadCount];
		if(typeof jsUrl!="undefined"){
			if (jsUrl.indexOf("?")>-1) 
				jsFilePathName = jsUrl.substring(0, jsUrl.indexOf("?"));
			else
				jsFilePathName = jsUrl;
			Milan.ajaxutility.loadJSFile(jsFilePathName,onLoadJs);
		}
	}
	
	
	
}


var loadCount=0;
//将页面上的table转成dhtmlXGrid,考虑到可能出现加载延迟的情况,这里做了一个延迟转换的处理,即如转换不成功,则每20毫秒去转化一次,连续20次,直到成功为止
//如果有传content参数，则先判断content参数中是否包含有需要转换的table,如不包含就直接return了
Milan.ajaxutility.transferGrid = function(container)
{
	//如果有传content参数，则先判断content参数中是否包含有需要转换的table,如不包含就直接return了
	var tables ;
	if (container)
		tables = jQuery(container).find("table.dhtmlxGrid").toArray();
	else
		tables = jQuery("table.dhtmlxGrid").toArray();

	if (tables.length==0) return;
	if (loadCount < 20) 
	{
		if (tables && tables.length > 0) 
		{
			
			for (var n = 0,nlen=tables.length; n < nlen; n++) 
			{						
				var table = tables[n];
				//Milan.ajaxutility.transferGrid.appendShowSelectColumn(table);
				var gridHeight = table.getAttribute("gridHeight");
				if (gridHeight)
				{
					if (gridHeight=="half")						//如果gridHeight为half,则为屏幕的一半大小
						gridHeight  = screen.availHeight/2
					table.setAttribute("gridHeight",gridHeight);
				}
				var grid = new dhtmlXGridFromTable(table.id,function(w){w.setImagePath(Milan.skinType+"images/dhtmlx/grid/");},true);
				
				grid.hiddenCols = ","+table.getAttribute("hiddencols")+",";//默认隐藏的列，格式如：hiddencols='流程名称,当前步骤,发起日期,状态'
				if(table.getAttribute("cannthiddencols")){
					grid.canntHiddenCols=","+table.getAttribute("cannthiddencols")+",";
				}else{
					grid.canntHiddenCols=","+grid.getColLabel(0)+",";
				}
				grid.enableLightMouseNavigation(false);
				grid.setEditable("off");
				grid.setSkin("default");
				
				//grid.enableMultiline(true);
				//如果table设置了gridHeight,则需要将其传入enableAutoHeight中
				if (gridHeight)
					grid.enableAutoHeight(true,parseInt(table.getAttribute("gridHeight"))-4,true,true);
				else
					grid.enableAutoHeight(true,null,null,true);
					
				if(grid.getRowsNum()==0){grid.objBox.style.overflow="hidden"}
					
				grid.id = table.id;
				grid.entBox.setAttribute("gridObjId",grid.id);
				if (!table.getAttribute("noSelectColumn"))
					Milan.ajaxutility.transferGrid.appendShowSelectColumn(grid);
				grid.originalOrder=grid.hdrLabels.clone();
				if(Milan.navigator.isAndroid)grid.enableAutoWidth(true);
				Milan.ajaxutility.addGridToCache(grid);
				//add by zhangml 2009-07-31
				// 实现从cookie中读取用户设置过的grid设置，并为宽度和列位置的设置添加存cookie的功能
				if(grid.enableColumnMove&&grid.needToCookie)grid.enableColumnMove(true);
				Milan.ajaxutility.revertGridByCookie(grid,false);
				//grid.hdr.oncontextmenu=function(){Milan.ajaxutility.showSelectColumn(grid);return false;};
				grid.attachEvent("onResizeEnd",function(obj){Milan.ajaxutility.setCookie(grid.id, Milan.ajaxutility.getSettingToJson(grid), 30);});
				grid.attachEvent("onAfterCMove",function(cInd,posInd){Milan.ajaxutility.setCookie(grid.id, Milan.ajaxutility.getSettingToJson(grid), 30);})
				if(table.getAttribute("groupby"))
				{
					grid.groupBy(grid.getColIndexByTitle(table.getAttribute("groupby")),eval(table.getAttribute("comparefun")));
				}
				
				//Milan.ajaxutility.transferGrid.resizeColumnWidth(grid);		//已整合至grid.setSizes()中
				grid.setSizes();
			}
			
			loadCount=0;
		}
		else 
		{
			setTimeout(Milan.ajaxutility.transferGrid, 20);
			loadCount++;
		}
	}
	else
	{
		loadCount=0;
		return;
	}
}



/**
 * 添加显示列图标。
 * @author lvpw
 */
Milan.ajaxutility.transferGrid.appendShowSelectColumn = function(grid) {
	var selectColumn = "<div style='position:absolute;top:8px' title='显示/隐藏列' class=\"icon ico-table-select\" id='grid_table_show_select_column_"+grid.id+"'>&nbsp;</div>"
	var showDiv = "<div class=\"popup_min\" id=\""+grid.id+"_columns\" style='position:absolute; top:26px; right:8px; display:none; width:120px;z-index:2'></div>";
	jQuery(grid.hdrBox).prepend(selectColumn).find(".icon").css("right",10);
	jQuery(grid.entBox).prepend(showDiv);
	var showTimer,hideTimer;
	jQuery("#grid_table_show_select_column_"+grid.id+",#"+grid.id+"_columns").hover(function(ev){
		clearTimeout(hideTimer);
		showTimer=setTimeout(function(){
			showSelectColumn(grid.id,ev);
		},300);
	},function(ev){
		clearTimeout(showTimer);
		hideTimer=setTimeout(function(){
			hideSelectColumn(ev);
		},400);
	});
	var showSelectColumn=function(gridId,ev){
		var div = jQuery("#"+gridId+"_columns");
		if(div.css("display")!="none")return;
		div.fadeIn("fast");
		var title = "";
		var html = "<div class=\"popup_min_in\"><div class=\"popup_min_inner\"><h2 class=\"popup_min_title\">显示/隐藏列</h2><div class=\"popup_min_con\"><ul class=\"ul\">";
		html +=  "<li  style=\"border-bottom:1px solid #ccc;\"><input type=\"checkbox\" id='checkedall' name='checkedall'/><label for=\"checkedall\">全 选</label></li>";
		for(var i = 0; i<grid.getColumnCount(); i++){
			title = ","+grid.getHeaderCol(i)+",";
			if(!grid.canntHiddenCols || grid.canntHiddenCols.indexOf(title)==-1){
				html = html +  "<li><input type=\"checkbox\" id='"+i+"' name='"+gridId+"' "+(grid.isColumnHidden(i)?"":"checked='checked'")+"/><label for=\""+i+"\">";
				html = html + grid.getHeaderTitle(grid.getHeaderCol(i));
				html = html + "</label></li>";
			}
		}
		html += "</ul></div></div></div>";
		div.html(html);
		
		var $childCheckList = div.find("input[name='"+gridId+"']");
		div.find("input[id='checkedall']").attr("checked",$childCheckList.length==$childCheckList.filter(":checked").length);
		
		$childCheckList.bind("click",function(){
			var obj = this;
			var show = 0;
			for(var i = 0; i<grid.getColumnCount(); i++)
				if(!grid.isColumnHidden(i))
					show++;

			if(show==1&&!obj.checked)
			{
				obj.checked = true;
				Milan.commonutils.createDelayNotifyModel('提示', '至少显示一列！');		
				return;
			}
			grid.setColumnHidden(obj.getAttribute('id'), !obj.checked);
			var cook = Milan.ajaxutility.getSettingToJson(grid);
			if(cook!="")
				Milan.ajaxutility.setCookie(gridId, cook , 30);
			//Milan.ajaxutility.transferGrid.resizeColumnWidth(grid);	//已整合至grid.setSizes()中
			grid.setSizes();//此处必须调用该方法，否则隐藏或者显示列时，会出现问题
			div.find("input[id='checkedall']").attr("checked",$childCheckList.length==$childCheckList.filter(":checked").length);
		
		});
			
		div.find("input[id='checkedall']").bind("click",function(){
			var obj = this;
			div.find("input[name='"+gridId+"']").each(function(i,ele){
				if((obj.checked&&!ele.checked)||(!obj.checked&&ele.checked)){
					ele.checked=obj.checked;
					grid.setColumnHidden(ele.getAttribute('id'), !ele.checked);
				}
			});
			var cook = Milan.ajaxutility.getSettingToJson(grid);
			if(cook!="")
				Milan.ajaxutility.setCookie(gridId, cook , 30);
			//Milan.ajaxutility.transferGrid.resizeColumnWidth(grid);	//已整合至grid.setSizes()中
			grid.setSizes();//此处必须调用该方法，否则隐藏或者显示列时，会出现问题
		});
		
		/*jQuery("div.popup_min_con").find("li").bind("click",function(){
			var obj = jQuery(this).find("input");
			var grid=Milan.ajaxutility.getGridFromCache(obj.attr('name'));
			if(!grid)
				return;
			var show = 0;
			for(var i = 0; i<grid.getColumnCount(); i++)
				if(!grid.isColumnHidden(i))
					show++;
			if(show==1&&!obj.attr('checked'))
			{
				obj.attr('checked',true);
				Milan.commonutils.createDelayNotifyModel('提示', '至少显示一列！');		
				return;
			}
			grid.setColumnHidden(obj.attr('id'), !obj.attr('checked'));
			var cook = Milan.ajaxutility.getSettingToJson(grid);
			if(cook!="")
				Milan.ajaxutility.setCookie(grid.id, cook , 30);
			Milan.ajaxutility.transferGrid.resizeColumnWidth(grid);
		});*/
	};
	var hideSelectColumn= function(ev){
		jQuery("div[id$='_columns']").fadeOut().html("");
	};
}  
/**
 * 根据hiddencols设置隐藏列
 */
Milan.ajaxutility.hideDefaultHiddenCols=function(grid,isCancel){
	var  len =grid.getColumnCount(),title='';
	if(isCancel)
	{
		for(var j=0,jlen=grid.originalOrder.length;j<jlen;j++){
			for(var l=0; l < len; l++){
			    if(grid.getHeaderCol(l)==grid.originalOrder[j]){
			    	if(l==j)break;
			    	grid.moveColumn(l,j);
			    	break;
			    }
			}
		}
	}
	for ( var i = 0; i < len; i++) {
		title = ","+grid.getHeaderCol(i)+",";
		grid.setColumnHidden(i, grid.hiddenCols && grid.hiddenCols.indexOf(title)>-1);
	}
};
/**
 * 根据cookie中的设置，显示grid
 * @author : zhangml
 */
Milan.ajaxutility.revertGridByCookie = function(grid,isCancel) {
	var cookies = Milan.ajaxutility.getCookie(grid.id);
	if (!cookies||cookies.indexOf(Milan.currentUserId)!=0){
		//add by zhangml 2009-11-23
		Milan.ajaxutility.hideDefaultHiddenCols(grid,isCancel);
		return;
	}
	var coos = cookies.split('/'), col;
	for ( var i = 1, clen = coos.length; i < clen; i++) {
		try{
		    col = eval("({" + coos[i] + "})");
		    for(var l=0,len = grid.getColumnCount(); l < len; l++)
		    	if(grid.getHeaderCol(l)==col.n)
		    		grid.OP(l,col.p);
		    if(col.h==0)grid.setColWidth(col.p,col.w);
		    grid.setColumnHidden(col.p,col.h==1);
		}catch(e){
			continue;
		}
	}
};
/**
 * 根据grid的设置，生成cookie内容
 * @author : zhangml
 */
Milan.ajaxutility.getSettingToJson = function(grid) {
	if(!grid.needToCookie)return "";
	var json = "", h = 0, len =grid.getColumnCount(), col = "";
	for ( var i = 0; i < len; i++) {
		h = (grid.isColumnHidden(i))?1:0;
		//每列含义：n:name,p:position,w:width,h:hidden（hidden==0时为显示状态，否则为隐藏）
		col = "n:\"" + grid.getHeaderCol(i) + "\",p:"+ i + ",w:" + grid.getColWidth(i)+ ",h:" + h + "/";
		json += col;
	}
	if(json.indexOf("h:0")<0){
		Milan.commonutils.createDelayNotifyModel('提示', '至少显示一列！');
		return "";
	}
	return json.substring(0, json.length - 1);
};




/**
 * grid实例缓存。
 * @author lvpw
 */
Milan.ajaxutility.grids = new Array();

/**
 * 缓存grid实例，每个id只缓存一个实例。
 * @author lvpw
 */
Milan.ajaxutility.addGridToCache = function (grid) {
	for(var i = 0; i<Milan.ajaxutility.grids.length; i++) {
		if(Milan.ajaxutility.grids[i].id==grid.id) {
			Milan.ajaxutility.grids[i] = grid;
			
			return;
		}
	}
	
	Milan.ajaxutility.grids[Milan.ajaxutility.grids.length] = grid;
};
Milan.ajaxutility.getGridFromCache = function(tableId){
	for(var i = 0; i<Milan.ajaxutility.grids.length; i++) {
		if(Milan.ajaxutility.grids[i].id==tableId) {
			return Milan.ajaxutility.grids[i];
		}
	}
	return null;
};
/**
 * 设置cookie
 * @author : zhangml
 */
Milan.ajaxutility.setCookie = function(cName, cValue, days,
		path, domain) {
	if(cValue=="")return;
	cValue=Milan.currentUserId+"/"+cValue;
	var c = cName + "=" + escape(cValue);
	if (days && typeof (days) == 'number') {
		var date = new Date();
		date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
		c += "; expires=" + date.toGMTString();
	}
	if (path && typeof (path) == 'string')
		c += "; path=" + path;
	if (domain && typeof (domain) == 'string')
		c += "; domain=" + domain;
	document.cookie = c;
};
/**
 * 根据cookie名称获取cookie
 * @author : zhangml
 */
Milan.ajaxutility.getCookie = function(cName) {
	var arg = cName + '=';
	var alen = arg.length;
	var clen = document.cookie.length;
	var i = 0;
	while (i < clen) {
		var j = i + alen;
		if (document.cookie.substring(i, j) == arg) {
			var endstr = document.cookie.indexOf(';', j);
			if (endstr == -1)
				endstr = document.cookie.length;
			return unescape(document.cookie.substring(j, endstr));
		}
		i = document.cookie.indexOf(' ', i) + 1;
		if (i == 0)
			break;
	}
	return null;
};
/**
 * 根据js文件的全路径名得到一个该方法的包路径
 * 例如给定：
 *         jsFileName="js/pageJS/page_top.js"
 * 则返回：Ext.milan.pagejs.page_top
 * 
 * @param {Object} jsFileName
 * @author : WinyWan
 */
Milan.ajaxutility.getPacketName = function(jsFileName)
{
	if(jsFileName.indexOf("?")>-1)
	    jsFileName = jsFileName.substring(0,jsFileName.indexOf("?"));
	if((!jsFileName)||jsFileName.length<1) return "";
	jsFileName = jsFileName.substring(2,jsFileName.length-3);
	var functionName ="";
    var jsFileNameArray = jsFileName.split("/");
	for(var i=0;i<jsFileNameArray.length;i++)
	{
		jsFileNameArray[i] = jsFileNameArray[i].toLowerCase();
	}
	for(var i=0;i<jsFileNameArray.length;i++)
	{
		functionName += jsFileNameArray[i]+".";
	}
	var returnFunc = "Ext.milan" + functionName;
	return returnFunc.substring(0,returnFunc.length-1);
}

/**
 * 根据页面中对于js的指示，加载js文件
 * 
 * @param {Object} response
 * @author : WinyWan
 */
Milan.ajaxutility.getJsFileName = function (response)
{
	return Milan.ajaxutility.getInfoFromResponseHead(response.responseText,"jsFileName");
}

Milan.ajaxutility.getJsContent = function(response)
{
	var content = response.responseText;
    //alert(content);
	var regxStr = '(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)';
	var scriptContentArray = [];
	var n = 0;
	var pattern = new RegExp(regxStr, 'img');
	var scripts = content.match(pattern);
	
	if (scripts) 
	{
		match = new RegExp(regxStr, 'im');
		for (var i = 0,ilen=scripts.length; i < ilen; i++) 
		{
			scriptContentArray[n++] = (scripts[i].match(match)[1]);
		}
	}
	return scriptContentArray;
}

Milan.ajaxutility.getInfoFromResponseHead = function(responseText,tagName)
{
	var responseContent = responseText;
	var jsFileIndexS = responseContent.indexOf("<"+tagName+">");
	var jsFileIndexE = responseContent.indexOf("</"+tagName+">");
	if(jsFileIndexS>=jsFileIndexE) return "";
	var jsFilePath = responseContent.substring(jsFileIndexS+2+tagName.length,jsFileIndexE);
	jsFilePath = jsFilePath.substring(jsFilePath.indexOf("<!--")+4,jsFilePath.indexOf("-->"));
	return jsFilePath.replace(/(^[\s]*)|([\s]*$)/g,"");
}



Milan.ajaxutility.isFunctionValid = function (functionName) {
	var vArray;
	if (functionName) 
	{
		if (functionName.trim().length==0) return false;
		var tempObjStr ;
		vArray = functionName.split(".");
		if(vArray.length>0) tempObjStr = vArray[0];
		if (tempObjStr.trim().length==0) return false;
		if(eval("typeof " + tempObjStr + "=='undefined'")) return false;
		for(var n=1,nlen=vArray.length;n<nlen;n++)
		{
			tempObjStr += "."+vArray[n];
			if(eval("typeof " + tempObjStr + "=='undefined'")) return false;
		}
		return true;
	} 
	else 
	{
		return false;
	}
};


/*
*	用于下载文件
* config参数目前有以下属性：
* url:请求的url,必须的
* form:要提交的表单，表单中可提交的内容将被放到url之后
* params:额外的参数，将被放到url之后
*/
Milan.ajaxutility.downloadFile = function(config)
{
    function _createDFrame()
    {    	
    		var iframe = document.createElement('IFRAME');
    		iframe.id = "__downloadIframe__"+(new Date()).getTime();
    		iframe.name = "__downloadIframe__"+(new Date()).getTime();
    		iframe.className = 'x-hidden';
    		return iframe;
    }
    
    function _generateUrl(config)
    {
    	if (typeof(config)=="string")
    	{
    		return config;
    	}
    	
			var url = config["url"];
			var tips = url.indexOf("?")>-1?"&":"?";

			if(config["form"])
				url+= tips +$(config["form"]).serialize()+"&"+config["param"];
			else
				url+= tips +config["param"];
				
			return url;
    }
    
    function _cb()
    {
    	var cbTimer = null;
    	try
    	{
	    	var doc ;
		    if(Milan.navigator.isIE)
                doc = downloadFrame.contentWindow.document;
            else 
                doc = (downloadFrame.contentDocument || window.frames["__downloadIframe__"].document);
				if(doc && doc.childNodes)
				{
					try
					{
						var message="";
						if(Milan.navigator.isIE)
							message = doc.XMLDocument.getElementsByTagName("error-message")[0].firstChild.nodeValue;
						else
							message=doc.getElementsByTagName("error-message")[0].firstChild.nodeValue;
						Milan.commonutils.createDelayNotifyModel('提示信息',message);
					}
					catch(e)
					{
						Milan.commonutils.createDelayNotifyModel('提示信息',"对不起，您所查看的文件已经被删除！");
					}
				}
				Event.stopObserving(downloadFrame, "load", _cb);
				if(cbTimer) clearTimeout(cbTimer);
    	}
    	catch(e)
    	{
    		if(loadCount>2)
    		{
    			if(cbTimer) clearTimeout(cbTimer);
    			Milan.commonutils.createDelayNotifyModel('提示信息',"对不起，您所查看的文件已经被删除！");
    			return ;
    		}
    		loadCount++;
    		cbTimer = setTimeout(_cb,500);
    	}
    }
    
    var downloadFrame = _createDFrame();
    document.body.appendChild(downloadFrame);
    var loadCount = 0;
    if(typeof(config)=="string" || typeof config["url"] != 'undefined'){
	    var url = _generateUrl(config);
    	downloadFrame.src = encodeURI(url);
    	Event.observe(downloadFrame, "load", _cb);
    }else{
    	var form = config["form"];
    	if(form){
    		form.target = downloadFrame.name;
    		form.submit();
    	}
    }

    setTimeout(function(){try{downloadFrame.parentNode.removeChild(downloadFrame);}catch(e){}}, 30000);	//remove downloadFrame after 30 seconds
}



